<template>
  <div class="page-mobile-collection">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="我的收藏"
    ></white-header>
    <div class="menu-list" v-if="kl_md.KLDLTK != 1 && kl_md.KLXBTK == 1">
      <div
        :class="['menu-item', action === 'course' ? 'active' : '']"
        @click="menuHandle('course')"
      >
        课程收藏
      </div>
      <div
        :class="['menu-item', action === 'question' ? 'active' : '']"
        @click="menuHandle('question')"
      >
        题库收藏
      </div>
    </div>
    <div class="course-list" v-if="action === 'course'">
      <collection-card
        v-for="(item, index) in courseList"
        :key="index"
        :detail="item.course"
      ></collection-card>
      <div class="footer" v-show="courseList.length > 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty
        description="暂无收藏哟~"
        v-show="courseList.length <= 0"
      />
    </div>
    <div class="question-list" v-if="action === 'question'">
      <div
        class="question"
        v-for="(item, index) in questionList"
        :key="index"
        @click="toChapter(item)"
      >
        <div class="tags">
          {{ index + 1 }}
        </div>
        <div class="question-title">
          {{ item.question.question }}
        </div>
        <div class="question-type">
          来源：章节练习-《{{ item.chapterName }}》
        </div>
      </div>
      <div class="footer" v-show="questionList.length > 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty description="暂无收藏哟~" v-show="questionList.length <= 0" />
    </div>
  </div>
</template>

<script>
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import CollectionCard from "~/components/mobile/CollectionCard.vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { getCollectList } from "~/api/v2-question-bank/question-bank.js";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader,
    CollectionCard
  },
  data() {
    return {
      that: this,
      action: "course",
      courseList: [], //收藏课程列表
      questionList: [], //题库收藏列表
      coursePageConfig: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      questionPageConfig: {
        total: 0,
        page: 1,
        pageSize: 10
      }
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      }
    })
  },
  watch: {},
  filters: {},
  destroyed() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  deactivated() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
      window.addEventListener("scroll", this.eventListener);
    }

    this.initPages();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.setLoading(false);
      this.initPages();
    });
  },
  methods: {
    ...mapActions([]),
    ...mapMutations(["SET_IS_LOADING"]),
    menuHandle(action) {
      this.action = action;
    },
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (
          (this.action === "course" &&
            this.coursePageConfig.total <= this.courseList.length) ||
          (this.action === "question" &&
            this.questionPageConfig.total <= this.questionList.length)
        ) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        if (this.action === "course") {
          this.coursePageConfig.page++;
          this.getCourseCollectionList("pullup");
        } else if (this.action === "question") {
          this.questionPageConfig.page++;
          this.getQuestionCollectionList("pullup");
        }
      }
    },
    toChapter(obj) {
      this.$router.push({
        path:
          "/m/v2-answer-sheet?id=" +
          obj.questionGroupId +
          "&type=0&chapterId=" +
          obj.chapterId +
          "&targetId=" +
          obj.targetId
      });
    },
    //获取课程收藏列表
    async getCourseCollectionList(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await getCollectList({
        sort: "id desc",
        offset:
          this.coursePageConfig.pageSize * (this.coursePageConfig.page - 1),
        limit: this.coursePageConfig.pageSize,
        userId: this.user_info.id,
        type: 1
      });
      if (result && result.data && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.courseList = [...this.courseList, ...result.data.data.rows];
        } else {
          this.courseList = result.data.data.rows;
        }
        this.coursePageConfig.total = result.data.data.total;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("获取失败！");
      }
    },
    //获取题库收藏列表
    async getQuestionCollectionList(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await getCollectList({
        sort: "id desc",
        offset:
          this.questionPageConfig.pageSize * (this.questionPageConfig.page - 1),
        limit: this.questionPageConfig.pageSize,
        userId: this.user_info.id,
        type: 3
      });
      if (result && result.data && result.data.code == 200) {
        if (fetch_type == "pullup") {
          let nextQuestionList = result.data.data.rows.map(item => {
            return {
              targetId: item.targetId,
              question: JSON.parse(item.questionGroupTestQuestion.question),
              chapterId: item.questionGroupChapter.id,
              chapterName: item.questionGroupChapter.chapterName
            };
          });
          this.questionList = [...this.questionList, ...nextQuestionList];
        } else {
          this.questionList = result.data.data.rows;
          this.questionList = this.questionList.map(item => {
            return {
              targetId: item.targetId,
              question: JSON.parse(item.questionGroupTestQuestion.question),
              questionGroupId: item.questionGroupTestQuestion.questionGroupId,
              chapterId: item.questionGroupChapter.id,
              chapterName: item.questionGroupChapter.chapterName
            };
          });
        }
        this.questionPageConfig.total = result.data.data.total;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("获取失败！");
      }
    },
    initPages() {
      this.coursePageConfig = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.questionPageConfig = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      if (this.kl_md.KLDLTK != 1) {
        this.getCourseCollectionList();
      }
      this.getQuestionCollectionList();
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
    }
    this.initPages();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.setLoading(false);
      this.initPages();
    });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-collection {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #ffffff;
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .menu-list {
    display: flex;
    justify-content: space-between;
    border-bottom: 0.0096rem solid #ededf1;
    .menu-item {
      width: 50%;
      background-color: #ffffff;
      height: 0.864rem;
      text-align: center;
      line-height: 0.864rem;
      font-size: 0.288rem;
      color: #9d9fa3;
      position: relative;
      &.active {
        color: #535557;
        &::before {
          content: "";
          display: block;
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 0.8rem;
          height: 0.04rem;
          background-color: var(--theme-color);
        }
      }
    }
  }
  .question-list {
    .question {
      width: 7.2rem;
      height: 1.536rem;
      padding: 0.36rem 0.288rem;
      border-bottom: 0.0096rem solid #ededf1;
      position: relative;
      .tags {
        position: absolute;
        left: 0.288rem;
        top: 0.36rem;
        width: 0.34rem;
        height: 0.34rem;
        line-height: 0.34rem;
        text-align: center;
        font-size: 0.2rem;
        font-weight: bold;
        color: var(--theme-color);
        border-radius: 50%;
        border: solid 0.0192rem var(--theme-color);
      }
      .question-title {
        width: 6rem;
        margin-left: 0.5rem;
        color: #4a4b4d;
        font-size: 0.2688rem;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-bottom: 0.15rem;
      }
      .question-type {
        width: 6rem;
        margin-left: 0.5rem;
        color: #4a4b4d;
        font-size: 0.2688rem;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: #949699;
      }
    }
  }
}
</style>
<style lang="scss">
.page-mobile-collection {
}
</style>
